package com.whccb.apps.office.document.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;

import com.actionsoft.bpms.bo.engine.BO;
import com.actionsoft.bpms.bpmn.engine.core.delegate.ProcessExecutionContext;
import com.actionsoft.bpms.bpmn.engine.servicetask.ServiceDelegate;
import com.actionsoft.bpms.commons.formfile.model.delegate.FormFile;
import com.actionsoft.bpms.server.fs.DCContext;
import com.actionsoft.bpms.util.DBSql;
import com.actionsoft.sdk.local.SDK;
import com.actionsoft.sdk.local.api.LogAPI;
import com.actionsoft.sdk.local.api.Logger;
import com.whccb.apps.office.document.ODConstant;
import com.whccb.apps.office.document.util.IWebOfficeUtil;
import com.whccb.apps.office.document.util.JodUtil;

public class CreatePDFService extends ServiceDelegate {

	private static final Logger logger = LogAPI.getLogger(CreatePDFService.class);
	
	public String getDescription() {
		return "将正文转成PDF文件,并将访问的URL存到BO的PDFURL字段上。";
	}

	public String getProvider() {
		return "ActionSoft";
	}

	public String getVersion() {
		return "AWS 6.0";
	}

	public boolean execute(ProcessExecutionContext pec) throws Exception {

		Map<String, Object> paramMap = SDK.getProcessAPI().getVariables(pec.getProcessInstance().getId());
		
		if (paramMap != null && !paramMap.isEmpty()) {
			
			String boName = paramMap.get("BONAME") != null ? paramMap.get("BONAME").toString() : "";
			BO bo = SDK.getBOAPI().getByProcess(boName, pec.getProcessInstance().getId());
			
			if (bo != null) {
				
				List<FormFile> formFileList = SDK.getBOAPI().getFiles(bo.getId(), "ZW");
				
				if (CollectionUtils.isNotEmpty(formFileList)) {
					FormFile zwFormFile = formFileList.get(0);
					if (zwFormFile != null) {
						DCContext zwDc = IWebOfficeUtil.getWebOfficeDc(zwFormFile);
						if (zwDc != null) {
							// 将正文DC转成PDF
							String url = JodUtil.fileToPdfAndUrl(pec.getUserContext().getSessionId(), zwDc,
									zwFormFile.getId(), ODConstant.APP_ID, bo.getId(), bo.getBindId(), boName,"PDFFILE");
							if (StringUtils.isNotBlank(url)) {
								url = url.substring(url.indexOf("&") + 1);
								String updateSql = " UPDATE " + boName + " SET PDFURL=:PDFURL WHERE ID = :ID ";
								Map<String, Object> param = new HashMap<String, Object>();
								param.put("PDFURL", url);
								param.put("ID", bo.getId());
								DBSql.update(updateSql, param);
							}
						}
						
					}
				}
			}
		}
		
		logger.info("-------pdf转换服务完成--------");
		
		return true;
	}
}
